package com.cqw.utils;

import com.cqw.common.HttpStatus;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Author: caoqingwen
 * @CreateTime: 2021-05-10 15:12
 * @Description: 客户端工具类
 */
public class ServletUtils {


    /**
     * 获取ServletRequestAttributes
     *
     * @return
     */
    public static ServletRequestAttributes getRequestAttributes() {
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        return (ServletRequestAttributes) requestAttributes;
    }


    /**
     * 获取request
     *
     * @return
     */
    public static HttpServletRequest getRequest() {
        ServletRequestAttributes requestAttributes = getRequestAttributes();
        return requestAttributes.getRequest();
    }


    /**
     * 将字符串渲染到客户端
     *
     * @param response
     * @param string
     */
    public static String sendString(HttpServletResponse response, String string) {

        try {

            response.setStatus(HttpStatus.SUCCESS);
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");
            response.getWriter().print(string);

        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
